package main

import (
	"fmt"
	"time"
)

//channel与select的应用场景：
//消息收发
//超时机制
//定时器

//channel与select的配合来完成客户端与服务端消息的收发
//应用：websocket的消息处理、同样应用于服务端一些时间的处理；比如：用户注册、订单支付成功以后的事件通知等等
//链接：https://www.bilibili.com/video/BV1EW4y147cX/?spm_id_from=333.788&vd_source=981ecfa8175498bbb21623e15803c777

func main() {
	//msgSendAndRecieve()
	timeOut()
}

// 看一下超时机制：
func timeOut() {
	doneCh := make(chan bool, 2)
	go func() {
		time.Sleep(5 * time.Second)
		doneCh <- true
	}()

	for {
		select {
		case <-doneCh:
			fmt.Println("time done")
		case <-time.After(time.Second * 3):
			fmt.Println("timeout")
		}
	}

	//select监听channel读操作，如果chanel有数据返回
}

// select的配合
func msgSendAndRecieve() {
	serverch := make(chan string, 10)
	clientch := make(chan string, 10)

	//服务端收发处理
	go func() {
		for {
			select {
			case msg, isfind := <-serverch:
				if !isfind {
					fmt.Println("server closed")
					break
				}
				fmt.Println("serverch read the msg is: ", msg)
				clientch <- fmt.Sprintf("reply to: %s", msg)
			}
		}
	}()

	//客户端的处理
	go func() {
		for {
			select {
			case msg, isfind := <-clientch:
				if !isfind {
					fmt.Println("clientch closed")
					break
				}
				fmt.Println("clientch recieve the msg is: ", msg)
			}
		}
	}()
	serverch <- "Let's go,I'm client"
	time.Sleep(3 * time.Second)
}
